package com.ten.goodsManager.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ten.goodsManager.common.exception.BusinessException;
import com.ten.goodsManager.common.exception.BusinessExceptionEnum;
import com.ten.goodsManager.common.vo.R;
import com.ten.goodsManager.common.vo.req.LoginReq;
import com.ten.goodsManager.user.mapper.UserMapper;
import com.ten.goodsManager.user.pojo.User;
import com.ten.goodsManager.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 86176
* @description 针对表【user(用户信息表)】的数据库操作Service实现
* @createDate 2024-06-15 21:10:04
*/
@Service
//@SofaService(interfaceType = UserService.class, uniqueId = "${service.unique.id}", bindings = { @SofaServiceBinding(bindingType = "bolt") })
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    private static final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Override
    public R login(LoginReq loginReq) {
        /**
         * 1.首先判断参数是否合法
         * 2.检查用户名和密码是否在表中
         * 3.在的话登录成功，生成token，返回给前端，且把信息放入SaToken
         * **/
        String username = loginReq.getUsername();
        String password = loginReq.getPassword();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new BusinessException(BusinessExceptionEnum.USERNAME_PASSWORD_NOT_NULL);
        }

        // 去查数据
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        queryWrapper.eq(User::getPassword, password);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(BusinessExceptionEnum.USERNAME_PASSWORD_ERROR);
        }

        // 查到，返回token给前端
        StpUtil.login(user.getUserId());  // 会自动返回
        // 打印当前登录人ID
        LOG.info("当前登录人ID:{}", StpUtil.getLoginId());
        List<User> users = queryUser(StpUtil.getLoginIdAsLong());
        LOG.info("当前用户角色为{}", users.get(0).getRole());
        return R.ok();
    }

    public List<User> queryUser(Long id) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (id != 0) {
            queryWrapper.eq(User::getUserId, id);
        }
        return userMapper.selectList(queryWrapper);
    }


}




